package com.cloudkinto.service.product.impl;

import cn.afterturn.easypoi.excel.entity.ExportParams;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cloudkinto.common.DicBusinessConstant;
import com.cloudkinto.common.DicBusinessItemConstant;
import com.cloudkinto.common.common.DateUtils;
import com.cloudkinto.common.constant.GlobalConstants;
import com.cloudkinto.common.constant.SysConstant;
import com.cloudkinto.common.exception.BizException;
import com.cloudkinto.common.exception.BizExceptionI18;
import com.cloudkinto.common.utils.ExcelUtils;
import com.cloudkinto.common.utils.MathUtils;
import com.cloudkinto.common.utils.TimeUtils;
import com.cloudkinto.common.utils.dict.StaticDict;
import com.cloudkinto.common.web.PageResult;
import com.cloudkinto.common.web.SingleResult;
import com.cloudkinto.dao.*;
import com.cloudkinto.entity.*;
import com.cloudkinto.extentity.product.MaterialDto;
import com.cloudkinto.service.dic.DicBusinessItemService;
import com.cloudkinto.service.dic.vo.DicItemRes;
import com.cloudkinto.service.file.FileService;
import com.cloudkinto.service.operate.OperateRecordService;
import com.cloudkinto.service.operate.impl.OperateRecordServiceImpl;
import com.cloudkinto.service.operate.vo.OperateRes;
import com.cloudkinto.service.orderoutput.OrderOutputProductService;
import com.cloudkinto.service.orderoutput.OrderOutputService;
import com.cloudkinto.service.orderoutput.vo.OrderOutputProductAddReq;
import com.cloudkinto.service.product.ProductCombinationService;
import com.cloudkinto.service.product.ProductInfoService;
import com.cloudkinto.service.product.vo.*;
import com.cloudkinto.service.product.vo.exportVo.ProductInfoExportVo;
import com.cloudkinto.service.shipprice.ShipPriceService;
import com.cloudkinto.service.stock.StockRecordService;
import com.cloudkinto.service.storageservice.StorageServiceProjectService;
import com.cloudkinto.service.storageservice.vo.StorageProjectRes;
import com.cloudkinto.utils.BarCodePdfUtils;
import com.cloudkinto.utils.PdfUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * service实现类
 * </p>
 *
 * @author 张永远
 * @since 2020-06-04
 */
@Service
@Transactional(rollbackFor = Exception.class)//事务回滚
public class ProductInfoServiceImpl extends ServiceImpl<ProductInfoDao, ProductInfoDo> implements ProductInfoService {
    @Autowired
    private ProductInfoDao dao;
    @Autowired
    private DicBusinessItemDao dicBusinessItemDao;
    @Autowired
    private ProductSkuMapDao productSkuMapDao;
    @Autowired
    private CompanyDao companyDao;
    @Autowired
    private FileService fileService;
    @Autowired
    private FileDao fileDao;
    @Autowired
    private OperateRecordService operateRecordDao;
    @Autowired
    private UserDao userDao;
    @Autowired
    private StorageServiceProjectDao storageServiceProjectDao;
    @Autowired
    private StorageServiceProjectService storageServiceProjectService;
    @Autowired
    private ProductCombinationDao combinationDao;
    @Autowired
    private ProductCombinationService productCombinationService;
    @Autowired
    private StockRecordService stockService;
    @Autowired
    private OrderOutputService orderOutputService;
    @Autowired
    private OrderOutputProductService orderOutputProductService;
    @Autowired
    private DicBusinessItemService dicBusinessItemService;
    @Autowired
    private StockRecordService stockRecordService;
    @Autowired
    private ShipPriceService mShipPriceService;

    private IPage<MaterialDto> pageInitM(Map<String, String> map) {
        IPage<MaterialDto> page = new Page();
        page.setSize(StringUtils.isNotBlank(map.get("pageSize")) ? Long.parseLong(map.get("pageSize")) : 10);
        page.setCurrent(StringUtils.isNotBlank(map.get("current")) ? Long.parseLong(map.get("current")) : 1);
        return page;
    }

    /**
     * 获取耗材
     */
    @Override
    public PageResult getMaterialList(Map<String, String> map) {
        //将长宽高排序
        if (StringUtils.isNotBlank(map.get("length")) && StringUtils.isNotBlank(map.get("width")) && StringUtils.isNotBlank(map.get("height"))) {
            double[] size = mShipPriceService.getSizeOrderDesc(Double.parseDouble(map.get("length")), Double.parseDouble(map.get("width")), Double.parseDouble(map.get("height")));
            map.put("longest", size[0]+"");
            map.put("minor", size[1]+"");
            map.put("shortest", size[2]+"");
        }

        IPage<MaterialDto> page = pageInitM(map);
        List<MaterialDto> list = dao.getMaterialList(page, map);
        List<MaterialRes> resList = new ArrayList<>();
        for (MaterialDto et : list) {
            MaterialRes res = new MaterialRes();
            BeanUtils.copyProperties(et, res);
            resList.add(res);
        }
        PageResult result = new PageResult(resList, (int) page.getCurrent(), (int) page.getSize(), (int) page.getTotal(), (int) page.getPages());
        return result;
    }

    @Override
    public SingleResult addInit() {
        List<List> list = new ArrayList<>();
        list.add(dicBusinessItemService.getDicItemList(DicBusinessConstant.productType));
        List<ProductInitRes> consumable = new ArrayList<>();
        //找到所有的标签id
        List<DicItemRes> ids = dicBusinessItemService.getDicItemList(32L);
        LambdaQueryWrapper<StorageServiceProjectDo> sspWrapper = new LambdaQueryWrapper<>();
        sspWrapper.in(StorageServiceProjectDo::getType, ids.stream().map(DicItemRes::getId).collect(Collectors.toList()));
        //得到id下的 所有值
        Map<Integer, List<StorageProjectRes>> storageServiceMap
                = storageServiceProjectService.getProjectList(ids.stream().map(DicItemRes::getId).collect(Collectors.toList())).stream()
                .collect(Collectors.groupingBy(StorageProjectRes::getType));
        for (DicItemRes id : ids) {
            ProductInitRes productInitRes = new ProductInitRes();
            productInitRes.setId(id.getId());
            productInitRes.setName(id.getValue());
            productInitRes.setStorageServiceProjectDos(storageServiceMap.get(id.getId().intValue()));
            if (productInitRes.getStorageServiceProjectDos() == null) {
                continue;
            }
            consumable.add(productInitRes);
        }
        list.add(consumable);
        SingleResult success = SingleResult.success(list);
        Map map = new HashMap();
        map.put("companyList", Arrays.asList(1, 2,3,4,300));
        success.setMapInfo(map);
        return success;
    }

    @Override
    public ProductAddReq add(ProductAddReq req, Long userId, Long companyId) {
        addCheck(req, companyId);
        ProductInfoDo entityDo = new ProductInfoDo();
        BeanUtils.copyProperties(req, entityDo);
        entityDo.setType(1);
        //对客户选择的耗材进行判断是否可以包裹
//        if (req.getConsumables() == null)
//            req.setConsumables(1L);
//        if (!req.getConsumables().equals(1L)) {
//            if ((req.getHeight() + req.getLength() + req.getWidth()) > storageServiceProjectDao
//                    .selectById(req.getConsumables()).getCapacity()) {
//                throw new BizExceptionI18(SysConstant.Product_Consumables_Error);
//            }
//        }
        entityDo.setCompanyId(companyId);
        if (req.getProductType() != null)
            entityDo.setProductType(req.getProductType());
        if (req.getCommoditySku() != null)
            entityDo.setCommoditySku(req.getCommoditySku().trim().replaceAll("\n", ""));
        handlerAddBefore(entityDo, userId);
        //前端新建的都是自费耗材
        entityDo.setCommonUse(1);
        //添加主表
        dao.insert(entityDo);
        operateRecordDao.operateAddRecord(SysConstant.OPERATE_CREATE_PRODUCT, entityDo.getId(), userId, 1);
//        addOperateRecord(entityDo, userId);

        //自动生成一个仓库sku
        CompanyDo companyDo = companyDao.selectById(companyId);
        String size = null;
        try {
            size = getSize(req.getHeight(), req.getLength(), req.getWidth());
        } catch (Exception e) {
            e.printStackTrace();
            throw new BizExceptionI18(SysConstant.Product_Size_Error, req.getCommoditySku());
        }
        String type = (req.getProductType() == null ? 0 : req.getProductType()) +"";
        String storageSku = req.getCommoditySku();
        if (!(companyId == null || companyId == 1 || companyId == 44 || companyId == 32) || StaticDict.Product_Info_Type.Material.getValue().equals(req.getTypeOfProduct())) {
            String code = StaticDict.Product_Info_Type.Combination.getValue().equals(req.getTypeOfProduct()) ? companyDo.getCompanyCode().replaceAll("C", "Z")
                    : (StaticDict.Product_Info_Type.Material.getValue().equals(req.getTypeOfProduct()) ? companyDo.getCompanyCode().replaceAll("C", "H") : companyDo.getCompanyCode());
            if (StaticDict.Product_Info_Type.Material.getValue().equals(req.getTypeOfProduct())) {
                type = "Y";//前端都是自费耗材
            }
            storageSku = size + type + code + entityDo.getId();
        }
        entityDo.setStorageSku(storageSku);
        dao.updateById(entityDo);

        //添加从表
        if (!CollectionUtils.isEmpty(req.getSkuMapAddReqList())) {
            for (ProductSkuMapAddReq mapAddReq : req.getSkuMapAddReqList()) {
                if (StringUtils.isEmpty(mapAddReq.getSubSku())) continue;
                mapAddReq.setSubSku(mapAddReq.getSubSku().trim());
                LambdaQueryWrapper<ProductSkuMapDo> wrapper2 = new LambdaQueryWrapper<>();
                wrapper2.eq(ProductSkuMapDo::getSubSku, mapAddReq.getSubSku()).eq(ProductSkuMapDo::getCompanyId, companyId);
                int count = this.productSkuMapDao.selectCount(wrapper2);
                if (count > 0) {
                    throw new BizExceptionI18(SysConstant.Product_ChildSku_Repeat, mapAddReq.getSubSku());
                }
                LambdaQueryWrapper<ProductInfoDo> wrapper3 = new LambdaQueryWrapper<>();
                wrapper3.eq(ProductInfoDo::getCommoditySku, mapAddReq.getSubSku())
                        .eq(ProductInfoDo::getCompanyId, companyId);
                int count1 = this.baseMapper.selectCount(wrapper3);
                if (count1 > 0) {
                    continue;
                }
                ProductSkuMapDo mapDo = new ProductSkuMapDo();
                mapDo.setProductInfoId(entityDo.getId());
                mapDo.setSubSku(mapAddReq.getSubSku());
                mapDo.setCompanyId(companyId);
                mapDo.setDeleteFlag(SysConstant.DELETE_FLAG_FALSE);
                productSkuMapDao.insert(mapDo);
            }
        }
        if (!StaticDict.Product_Info_Type.Material.getValue().equals(req.getTypeOfProduct()) && req.getChildIds() != null) {
            for (ProductChildAddReq childId : req.getChildIds()) {
                ProductCombinationDo combinationDo = new ProductCombinationDo();
                combinationDo.setParentId(entityDo.getId());
                combinationDo.setChildId(childId.getId());
                combinationDo.setCount(childId.getCount());
                combinationDo.setCreateTime(new Date());
                combinationDo.setEffective(childId.getEffective());
                combinationDo.setEffectBeginTime(childId.getEffectBeginTime());
                combinationDo.setEffectEndTime(childId.getEffectEndTime());
                combinationDao.insert(combinationDo);
            }

        }


        //文件操作
        fileService.uploadFile(entityDo.getProductPictureFileId());

        return req;
    }

    private String getSize(Float width, Float height, Float length) {
        int isize = 0;
        float size = width + height + length;
        int[] sizes = new int[]{60, 100, 160, 200, 260};
        for (int i :
                sizes) {
            if ((int) size < i) {
                isize = i;
                break;
            }
        }
        if (isize < 100) {
            return ("0" + isize).substring(0, 2);
        } else {
            return (isize + "").substring(0, 2);
        }
    }
//
//    private void addOperateRecord(ProductInfoDo entityDo, Long userId) {
//        OperateRecordDo operateRecordDo = new OperateRecordDo();
//        operateRecordDo.setContent("创建了一个商品");
//        operateRecordDo.setOperateBy(userId);
//        operateRecordDo.setType(1);
//        operateRecordDo.setThirdId(entityDo.getId());
//        operateRecordDo.setDeleteFlag(0);
//        operateRecordDo.setOperateTime(new Date());
//        operateRecordDao.insert(operateRecordDo);
//    }

    //新增校验
    private void addCheck(ProductAddReq req, Long companyId) {
        LambdaQueryWrapper<ProductInfoDo> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ProductInfoDo::getCommoditySku, req.getCommoditySku())
                .eq(ProductInfoDo::getCompanyId, companyId);
//                .eq(ProductInfoDo::getType, 1);
        int count = this.baseMapper.selectCount(wrapper);
        if (count > 0) {
            throw new BizExceptionI18(SysConstant.Product_Sku_Repeat, req.getCommoditySku());
        }
        this.checkCombination(req.getTypeOfProduct(), req.getChildIds(), req.getMaterialId());
    }

    public void checkCombination(String typeOfProduct, List<ProductChildAddReq> childIds, Long materialId) {
        if (StaticDict.Product_Info_Type.Combination.getValue().equals(typeOfProduct)) {
            //组合产品
            if (childIds == null || childIds.size() == 0) {
                throw new BizException(SysConstant.Product_Combination_Must_Choose_Child);
            }
            boolean flag = true;
            for (ProductChildAddReq childId : childIds) {
                if (childId.getEffective() == 0) {
                    flag = false;
                }
                if (childId.getEffective() == 1 && (childId.getEffectBeginTime() == null)) {
                    throw new BizException(SysConstant.Product_Combination_Choose_Effective_TIME);
                }
            }
            if (flag) {
                //组合产品 有一个 没有生效时期的子产品
                throw new BizException(SysConstant.Product_Combination_Effective);
            }
//            if (childIds != null && childIds.size() > 0) {
            List<Long> idds = childIds.stream().map(ProductChildAddReq::getId).collect(Collectors.toList());
            int count1 = dao.selectCount(new LambdaQueryWrapper<ProductInfoDo>().in(ProductInfoDo::getId, idds)
                    .eq(ProductInfoDo::getTypeOfProduct, StaticDict.Product_Info_Type.Combination.getValue()));
            if (count1 > 0) {
                throw new BizException(SysConstant.Product_Consumables_CannotChoose);
            }
//            }
        }
        else if (StaticDict.Product_Info_Type.Material.getValue().equals(typeOfProduct)) {
            //耗材 不能在选择耗材id
            if (materialId != null) {
                throw new BizException(SysConstant.Product_Consumables_CannotChoose);
            }
        }
    }

    //做新增之前要执行的业务定制处理
    private void handlerAddBefore(ProductInfoDo entityDo, Long userId) {
        entityDo.setCreateBy(userId);
        entityDo.setCreateTime(new Date());
        entityDo.setDeleteFlag(SysConstant.DELETE_FLAG_FALSE);
        //区分大小件
        this.jugSizeType(entityDo);

    }

    public void jugSizeType(ProductInfoDo entityDo) {
        //区分大小件
        if (entityDo.getSizeType() == null || entityDo.getSizeType() != 2) {
            if (entityDo.getLength() * entityDo.getWidth() * entityDo.getHeight() >= 80 || entityDo.getWeight() >= 15) {
                entityDo.setSizeType(1);
            }
        }
        if (StaticDict.Product_Info_Type.Material.getValue().equals(entityDo.getTypeOfProduct())) {
            entityDo.setProductType(StaticDict.Product_Type.Common_Material.getValue());
        }
    }


    @Override
    public SingleResult updateInit(Long id) {
        Map resultMap = new HashMap();
        resultMap.put("productTypeList", addInit().getData());

        ProductDetailRes detailRes = detailAll(id);
        resultMap.put("detail", detailRes);

        return SingleResult.success(resultMap);
    }

    @Override
    public void deleteProductFile(Long id) {
        ProductInfoDo old = dao.selectObject(id);
        if (old == null || old.getProductPictureFileId() == null) {
            return;
        }
        fileService.deleteFile(old.getProductPictureFileId());
        LambdaUpdateWrapper<ProductInfoDo> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(ProductInfoDo::getId, id);
        updateWrapper.set(ProductInfoDo::getProductPictureFileId, null);
        this.update(updateWrapper);
    }


    @Override
    public ProductUpdateReq update(ProductUpdateReq req, Long userId, Long companyId) {
        updateCheck(req, companyId);
        ProductInfoDo old = dao.selectObject(req.getId());
        float width = old.getWidth();
        float length = old.getLength();
        float height = old.getHeight();
        float weight = old.getWeight();
        String productName = old.getProductName();

        Long oldMaterialId = old.getMaterialId();

        ProductInfoDo entityDo = dao.selectObject(req.getId());
        if (!entityDo.getCommoditySku().equals(req.getCommoditySku())) {
            throw new BizExceptionI18(SysConstant.Product_Sku_Edit);
        }
        boolean sizeChangeFlag = this.operateRecord(req, entityDo, userId);
        String typeOfProduct = entityDo.getTypeOfProduct();
        if (StaticDict.Product_Info_Type.Combination.getValue().equals(typeOfProduct)) {
            //组合产品
//            if (req.getChildIds() == null || req.getChildIds().size() == 0) {
//                throw new BizException("组合产品请选择 子产品");
//            }
            if (req.getChildIds() != null && req.getChildIds().size() > 0) {
                List<Long> idds = req.getChildIds().stream().map(ProductChildAddReq::getId).collect(Collectors.toList());
                int count1 = dao.selectCount(new LambdaQueryWrapper<ProductInfoDo>().in(ProductInfoDo::getId, idds).eq(ProductInfoDo::getTypeOfProduct, StaticDict.Product_Info_Type.Combination.getValue()));
                if (count1 > 0) {
                    throw new BizExceptionI18(SysConstant.Product_Consumables_CannotChoose);
                }
            }
        }

        //操作文件
        if (req.getProductPictureFileId() != null && !req.getProductPictureFileId().equals(entityDo.getProductPictureFileId())) {
            fileService.uploadFile(req.getProductPictureFileId());
//            fileService.deleteFile(entityDo.getProductPictureFileId());
//            fileService.uploadFile2(req.getProductPictureFileId(), entityDo.getProductPictureFileId());
        }

        BeanUtils.copyProperties(req, entityDo);
        if (req.getProductType() != null) {
            entityDo.setProductType(req.getProductType());
        }
        entityDo.setType(1);
        if (sizeChangeFlag && entityDo.getNeedMeasure() == 0) {
            entityDo.setNeedMeasure(1);
            entityDo.setLengthStore(entityDo.getLength());
            entityDo.setWidthStore(entityDo.getWidth());
            entityDo.setHeightStore(entityDo.getWidth());
        }
        handlerUpdateBefore(entityDo, userId);
        if (entityDo.getDeleteFlag() == 1) {
            dao.updateObject(entityDo.getId(), 0);
            dao.updateById(entityDo);
            dao.updateObject(entityDo.getId(), 1);
        } else {
            dao.updateById(entityDo);
        }
        if (oldMaterialId != null && req.getMaterialId() == null) {
            LambdaUpdateWrapper<ProductInfoDo> updateWrapper = new LambdaUpdateWrapper<ProductInfoDo>();
            updateWrapper.eq(ProductInfoDo::getId, req.getId());
            updateWrapper.set(ProductInfoDo::getMaterialId, null);
            this.update(updateWrapper);
            ProductInfoDo productInfoDo = dao.selectObject(oldMaterialId);
            operateRecordDao.operateAddRecordAndValue(SysConstant.OPERATE_DELETE_PRODUCT_MATERIAL,
                    productInfoDo != null ? productInfoDo.getCommoditySku() : "未识别耗材", entityDo.getId(), userId, 1);

        }
        else if (oldMaterialId != null && req.getMaterialId() != null && !oldMaterialId.equals(req.getMaterialId())) {
            ProductInfoDo oldM = dao.selectObject(oldMaterialId);
            ProductInfoDo newM = dao.selectObject(req.getMaterialId());
            operateRecordDao.operateAddRecordAndValue(SysConstant.OPERATE_UPDATE_PRODUCT_MATERIAL,
                    oldM.getCommoditySku()+OperateRecordServiceImpl.operateRecordSeparator + newM.getCommoditySku(), entityDo.getId(), userId, 1);
        }
        else if (oldMaterialId == null && req.getMaterialId() != null) {
            ProductInfoDo newM = dao.selectObject(req.getMaterialId());
            operateRecordDao.operateAddRecordAndValue(SysConstant.OPERATE_ADD_PRODUCT_MATERIAL,
                     newM.getCommoditySku(), entityDo.getId(), userId, 1);
        }

        //修改从表
        LambdaQueryWrapper<ProductSkuMapDo> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ProductSkuMapDo::getProductInfoId, req.getId()).eq(ProductSkuMapDo::getCompanyId, entityDo.getCompanyId());
        productSkuMapDao.delete(wrapper);

        if (!CollectionUtils.isEmpty(req.getSkuMapAddReqList())) {
            for (ProductSkuMapAddReq skuMapAddReq : req.getSkuMapAddReqList()) {
                if (StringUtils.isEmpty(skuMapAddReq.getSubSku())) continue;
                skuMapAddReq.setSubSku(skuMapAddReq.getSubSku().trim());
                LambdaQueryWrapper<ProductSkuMapDo> wrapper2 = new LambdaQueryWrapper<>();
                wrapper2.eq(ProductSkuMapDo::getSubSku, skuMapAddReq.getSubSku())
                        .eq(ProductSkuMapDo::getCompanyId, companyId);
                int count = this.productSkuMapDao.selectCount(wrapper2);
                if (count > 0) {
                    throw new BizExceptionI18(SysConstant.Product_ChildSku_Repeat, skuMapAddReq.getSubSku());
                }
                LambdaQueryWrapper<ProductInfoDo> wrapper3 = new LambdaQueryWrapper<>();
                wrapper3.eq(ProductInfoDo::getCommoditySku, skuMapAddReq.getSubSku())
                        .eq(ProductInfoDo::getCompanyId, companyId);
                int count1 = this.baseMapper.selectCount(wrapper3);
                if (count1 > 0) {
                    throw new BizExceptionI18(SysConstant.Product_Sku_Repeat, skuMapAddReq.getSubSku());
                }
                ProductSkuMapDo skuMapDo = new ProductSkuMapDo();
                skuMapDo.setSubSku(skuMapAddReq.getSubSku());
                skuMapDo.setProductInfoId(req.getId());
                skuMapDo.setCompanyId(entityDo.getCompanyId());
                skuMapDo.setDeleteFlag(SysConstant.DELETE_FLAG_FALSE);
                productSkuMapDao.insert(skuMapDo);
            }
        }

        //组合产品
        if (!StaticDict.Product_Info_Type.Material.getValue().equals(typeOfProduct)) {
            LambdaQueryWrapper<ProductCombinationDo> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(ProductCombinationDo::getParentId, entityDo.getId());
            if (req.getChildIds() != null && req.getChildIds().size() > 0) {
                List<Long> idds = req.getChildIds().stream().map(ProductChildAddReq::getId).collect(Collectors.toList());
                queryWrapper.notIn(ProductCombinationDo::getChildId, idds);
            }
            List<Long> deleteIds = combinationDao.selectList(queryWrapper).stream().map(ProductCombinationDo::getId).collect(Collectors.toList());
            if (deleteIds.size() > 0) {
                combinationDao.deleteBatchIds(deleteIds);
            }
            if (req.getChildIds() != null) {
                for (ProductChildAddReq childId : req.getChildIds()) {
                    if (entityDo.getId().equals(childId.getId())) {
                        continue;
                    }
                    ProductCombinationDo combinationDo = combinationDao.selectOne(new LambdaQueryWrapper<ProductCombinationDo>()
                            .eq(ProductCombinationDo::getParentId, entityDo.getId()).eq(ProductCombinationDo::getChildId, childId.getId()));
                    if (combinationDo == null) {
                        combinationDo = new ProductCombinationDo();
                        combinationDo.setParentId(entityDo.getId());
                        combinationDo.setChildId(childId.getId());
                        combinationDo.setCreateTime(new Date());
                    }
                    combinationDo.setCount(childId.getCount());
                    combinationDo.setEffective(childId.getEffective());
                    combinationDo.setEffectBeginTime(childId.getEffectBeginTime());
                    combinationDo.setEffectEndTime(childId.getEffectEndTime());
                    if (combinationDo.getId() == null) {
                        combinationDao.insert(combinationDo);
                    }
                    else {
                        combinationDao.updateById(combinationDo);
                        if (combinationDo.getEffective() == 0) {
                            //无生效时间
                            LambdaUpdateWrapper<ProductCombinationDo> updateWrapper = new LambdaUpdateWrapper<>();
                            updateWrapper.set(ProductCombinationDo::getEffective, 0);
                            updateWrapper.set(ProductCombinationDo::getEffectBeginTime, null);
                            updateWrapper.set(ProductCombinationDo::getEffectEndTime, null);
                            updateWrapper.eq(ProductCombinationDo::getId, combinationDo.getId());
                            combinationDao.update(null, updateWrapper);
                        }
                    }
                }
            }
        }
        ProductInfoDo newDo = dao.selectObject(req.getId());
        if (!StaticDict.Product_Info_Type.Material.getValue().equals(typeOfProduct) && (length != newDo.getLength() || weight != newDo.getWeight() || height != newDo.getHeight() || width != newDo.getWidth())) {
            //修改了尺寸重量信息 冻结所有库存
            stockRecordService.freezeStock(entityDo.getId(), userId);
        }
        if (!productName.equals(entityDo.getProductName()) || sizeChangeFlag) {
            //推送到temu todo
        }

        return req;
    }

    private boolean operateRecord(ProductUpdateReq req, ProductInfoDo entityDo, Long userId) {
        boolean flag = false;
        float v = MathUtils.numberFormat(req.getHeight() * req.getLength() * req.getWidth(), 2);
        float v1 = MathUtils.numberFormat(entityDo.getLength() * entityDo.getWidth() * entityDo.getHeight(), 2);
        if (v != v1 && req.getWeight() != entityDo.getWeight()) {
            //同时修改了 三边和 和 重量
            operateRecordDao.operateAddRecordAndValue(SysConstant.OPERATE_UPDATE_PRODUCT_DETAIL,
                    entityDo.getLength() +"*"+ entityDo.getWidth() +"*"+ entityDo.getHeight() + OperateRecordServiceImpl.operateRecordSeparator +
                            req.getLength() +"*"+ req.getWidth() +"*"+ req.getHeight() + OperateRecordServiceImpl.operateRecordSeparator +
                            entityDo.getWeight() + OperateRecordServiceImpl.operateRecordSeparator + req.getWeight(), entityDo.getId(), userId, 1);
            flag = true;
        }
        else if (v != v1) {
            operateRecordDao.operateAddRecordAndValue(SysConstant.OPERATE_UPDATE_PRODUCT_SIZE_DETAIL,
                    entityDo.getLength() +"*"+ entityDo.getWidth() +"*"+ entityDo.getHeight() + OperateRecordServiceImpl.operateRecordSeparator +
                            req.getLength() +"*"+ req.getWidth() +"*"+ req.getHeight(), entityDo.getId(), userId, 1);
            flag = true;
        }
        else if (req.getWeight() != entityDo.getWeight()) {
            operateRecordDao.operateAddRecordAndValue(SysConstant.OPERATE_UPDATE_PRODUCT_WEIGHT_DETAIL,
                    entityDo.getWeight() + OperateRecordServiceImpl.operateRecordSeparator + req.getWeight(), entityDo.getId(), userId, 1);
            flag = true;
        }
        return flag;
    }

    //编辑校验
    private void updateCheck(ProductUpdateReq req, Long companyId) {
        LambdaQueryWrapper<ProductInfoDo> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ProductInfoDo::getCommoditySku, req.getCommoditySku())
                .eq(ProductInfoDo::getCompanyId, companyId)
                .eq(ProductInfoDo::getType, 1)
                .ne(ProductInfoDo::getId, req.getId());
        int count = this.baseMapper.selectCount(wrapper);
        if (count > 0) {
            throw new BizExceptionI18(SysConstant.Product_Sku_Repeat, req.getCommoditySku());
        }
        this.checkCombination(req.getTypeOfProduct(), req.getChildIds(), req.getMaterialId());
    }

    //做修改之前要执行的业务定制处理
    private void handlerUpdateBefore(ProductInfoDo entityDo, Long userId) {
        entityDo.setUpdateBy(userId);
        entityDo.setUpdateTime(new Date());
        this.jugSizeType(entityDo);

    }

    @Override
    public int delete(Long id, Long userId) {
        ProductInfoDo entityDo = dao.selectObject(id);
        switch (entityDo.getDeleteFlag().hashCode()) {
            case 0:
                LambdaQueryWrapper<StockRecordDo> recordDoLambdaQueryWrapper = new LambdaQueryWrapper<>();
                recordDoLambdaQueryWrapper.eq(StockRecordDo::getProductInfoId, entityDo.getId());
                List<StockRecordDo> stockRecordDos = stockService.getBaseMapper().selectList(recordDoLambdaQueryWrapper);
                int sum = stockRecordDos.stream().mapToInt(s -> s.getCanSellCount() + s.getCanotSellCount()).sum();
                if (sum > 0) {
                    throw new BizExceptionI18(SysConstant.Product_Delete_Fair_Stock);
                }
                LambdaQueryWrapper<OrderOutputDo> orderOutputDoLambdaQueryWrapper = new LambdaQueryWrapper<>();
                orderOutputDoLambdaQueryWrapper.eq(OrderOutputDo::getCompanyId, entityDo.getCompanyId());
                orderOutputDoLambdaQueryWrapper.lt(OrderOutputDo::getStatus, DicBusinessItemConstant.outSendOut);
                orderOutputDoLambdaQueryWrapper.gt(OrderOutputDo::getSendDate, TimeUtils.getCurrentDateFormat(-30));
                List<OrderOutputDo> orderOutputDos = orderOutputService.getBaseMapper().selectList(orderOutputDoLambdaQueryWrapper);
                List<Long> collect = orderOutputDos.stream().map(OrderOutputDo::getId).collect(Collectors.toList());
                if (collect.size() > 0) {
                    LambdaQueryWrapper<OrderOutputProductDo> orderOutputProductWrapper = new LambdaQueryWrapper<>();
                    orderOutputProductWrapper.in(OrderOutputProductDo::getOrderId, collect);
                    orderOutputProductWrapper.eq(OrderOutputProductDo::getProductId, entityDo.getId());
                    List<OrderOutputProductDo> productDoList = orderOutputProductService.getBaseMapper().selectList(orderOutputProductWrapper);
                    int orderCount = productDoList.stream().mapToInt(s -> s.getCount()).sum();
                    if (orderCount > 0) {
                        throw new BizExceptionI18(SysConstant.Product_Delete_Fair_ExistOrder);
                    }
                }
                entityDo.setDeleteFlag(1);
                break;
            case 1:
                int count = dao.selectCount(new LambdaQueryWrapper<ProductInfoDo>().eq(ProductInfoDo::getCommoditySku,entityDo.getCommoditySku()).eq(ProductInfoDo::getDeleteFlag,0));
                if (count>0){
                    throw new BizExceptionI18(SysConstant.Product_Sku_Repeat);
                }
                entityDo.setDeleteFlag(0);
                break;
        }
        dao.updateObject(id, entityDo.getDeleteFlag());
        return 1;
    }

    //做删除之前要执行的业务定制处理
    private void handlerDeleteBefore(ProductInfoDo entityDo, Long userId) {
        entityDo.setDeleteBy(userId);
        entityDo.setDeleteTime(new Date());
    }

    @Override
    public ProductDetailRes detail(Long id) {
        ProductDetailRes detail = detailAll(id);
        //操作日志
        List<OperateRes> operateResList  = operateRecordDao.getOperateList(id,1);
        detail.setOperateResList(operateResList);
//        if (detail.getConsumables() != null)
//            switch (detail.getConsumables().toString()) {
//                case "0":
//                    detail.setConsumablesName("暂未选择耗材");
//                    break;
//                case "1":
//                    detail.setConsumablesName("无需耗材");
//                    break;
//                default:
//                    detail.setConsumablesName(storageServiceProjectDao
//                            .selectById(detail.getConsumables()).getProjectName());
//            }
        return detail;
    }

    @Override
    public Long getProductId(String sellerSKu, Long companyId) {
        final String sellerSku = sellerSKu.trim().replaceAll("\\n", "").replaceAll("　", "");
        LambdaQueryWrapper<ProductInfoDo> productWrapper = new LambdaQueryWrapper();
        productWrapper.eq(ProductInfoDo::getCompanyId, companyId);
        productWrapper.and(product -> {
            product.eq(ProductInfoDo::getCommoditySku, sellerSku).or().eq(ProductInfoDo::getStorageSku, sellerSku);
        });
        ProductInfoDo productInfoDo = dao.selectOne(productWrapper);
        if (productInfoDo == null) {
            QueryWrapper skuWrapper = new QueryWrapper();
            skuWrapper.eq("sub_sku", sellerSku);
            skuWrapper.eq("company_id", companyId);
            ProductSkuMapDo productSkuMapDo = productSkuMapDao.selectOne(skuWrapper);
            if (productSkuMapDo == null) return null;
            return productSkuMapDo.getProductInfoId();
        } else {
            return productInfoDo.getId();
        }
    }


    @Override
    public ProductInfoDo getProductDo(String sellerSKu, Long companyId) {
        final String sellerSku = sellerSKu.trim().replaceAll("\\n", "").replaceAll("　", "");
        LambdaQueryWrapper<ProductInfoDo> productWrapper = new LambdaQueryWrapper();
        productWrapper.eq(ProductInfoDo::getCompanyId, companyId);
        productWrapper.and(product -> {
            product.eq(ProductInfoDo::getCommoditySku, sellerSku).or().eq(ProductInfoDo::getStorageSku, sellerSku);
        });
        ProductInfoDo productInfoDo = dao.selectOne(productWrapper);
        if (productInfoDo == null) {
            QueryWrapper skuWrapper = new QueryWrapper();
            skuWrapper.eq("sub_sku", sellerSku);
            skuWrapper.eq("company_id", companyId);
            ProductSkuMapDo productSkuMapDo = productSkuMapDao.selectOne(skuWrapper);
            if (productSkuMapDo == null) return null;
            return dao.selectById(productSkuMapDo.getProductInfoId());
        } else {
            return productInfoDo;
        }
    }


    @Override
    public List<OrderOutputProductAddReq> getProductDoReturnAddReq(String sku, Integer quantity, Long companyId) {
        ProductInfoDo productInfoDo = getProductDo(sku, companyId);
        List<OrderOutputProductAddReq> itemAddReqList = new ArrayList<>();
        if (!productInfoDo.getTypeOfProduct().equals(StaticDict.Product_Info_Type.Combination.getValue())) {
            OrderOutputProductAddReq productDo1 = new OrderOutputProductAddReq();
            productDo1.setProductId(productInfoDo.getId());
            productDo1.setCommoditySku(productInfoDo.getCommoditySku());
            productDo1.setCount(quantity);
            itemAddReqList.add(productDo1);
        } else {
            LambdaQueryWrapper<ProductCombinationDo> productCombinationWrapper = new LambdaQueryWrapper<>();
            productCombinationWrapper.eq(ProductCombinationDo::getParentId, productInfoDo.getId());
            List<ProductCombinationDo> productCombinationDoList = productCombinationService.getBaseMapper().selectList(productCombinationWrapper);
            for (ProductCombinationDo productCombinationDo : productCombinationDoList) {
                OrderOutputProductAddReq productDo1 = new OrderOutputProductAddReq();
                ProductInfoDo productInfoDo1 = getById(productCombinationDo.getChildId());
                if (productInfoDo1 == null) continue;
                productDo1.setProductId(productCombinationDo.getChildId());
                productDo1.setCommoditySku(productInfoDo1.getCommoditySku());
                productDo1.setCount(productCombinationDo.getCount());
                itemAddReqList.add(productDo1);
            }
        }
        return itemAddReqList;
    }

    @Override
    public Collection<? extends OrderOutputProductAddReq> getAddProductListByPlatformSku(Long companyId, Date date, String orderNumber, String itemSku, Integer count) {
        List<OrderOutputProductAddReq> productDoList=new ArrayList<>();
        if (itemSku.contains("+")) {
            for (String sku :itemSku.split("\\+")) {
                OrderOutputProductAddReq productDo1 = new OrderOutputProductAddReq();
                productDo1.setProductId(getProductId(sku, companyId));
                productDo1.setCommoditySku(sku);
                productDo1.setCount(count);
                productDoList.add(productDo1);
            }
        } else {
            ProductInfoDo productInfoDo = getProductDo(itemSku,companyId);
            if (productInfoDo == null) {
                OrderOutputProductAddReq productDo1 = new OrderOutputProductAddReq();
                productDo1.setProductId(null);
                productDo1.setCommoditySku(itemSku);
                productDo1.setCount(count);
                productDoList.add(productDo1);
                return productDoList;
                // throw new BizExceptionI18(SysConstant.ORDER_NO_SKU_INFO2_ID, orderNumber, itemSku);
//                        throw new BizException(String.format("%s(未找到%s信息)", rakutenDo.getOrderNumber(), productDo.getItemNumber()));
            }
            LambdaQueryWrapper<ProductCombinationDo> productCombinationWrapper = new LambdaQueryWrapper<>();
            productCombinationWrapper.eq(ProductCombinationDo::getParentId, productInfoDo.getId());
            List<ProductCombinationDo> productCombinationDoList = productCombinationService.getBaseMapper().selectList(productCombinationWrapper);
            for (ProductCombinationDo productCombinationDo : productCombinationDoList) {
                if (productCombinationDo.getEffective() == 1) {
                    if (productCombinationDo.getEffectBeginTime() == null || productCombinationDo.getEffectEndTime() == null)
                        continue;
                    if (date.getTime() < productCombinationDo.getEffectBeginTime().getTime()
                            || date.getTime() > productCombinationDo.getEffectEndTime().getTime())
                        continue;
                }
                OrderOutputProductAddReq productDo1 = new OrderOutputProductAddReq();
                ProductInfoDo productInfoDo1 = getById(productCombinationDo.getChildId());
                if (productInfoDo1 == null) {
                    continue;
                    // throw new BizExceptionI18(SysConstant.ORDER_NO_SKU_GROUP_INFO_ID, itemSku, productInfoDo.getCommoditySku());
//                                throw new BizException(String.format("%s(未找到%s的组合产品信息)", rakutenDo.getOrderNumber(), productInfoDo.getCommoditySku()));
                }
                productDo1.setProductId(productCombinationDo.getChildId());
                productDo1.setCommoditySku(productInfoDo1.getCommoditySku());
                productDo1.setCount(count * productCombinationDo.getCount());
                productDoList.add(productDo1);
            }
            if (!productInfoDo.getTypeOfProduct().equals(StaticDict.Product_Info_Type.Combination.getValue())) {
                OrderOutputProductAddReq productDo1 = new OrderOutputProductAddReq();
                productDo1.setProductId(productInfoDo.getId());
                productDo1.setCommoditySku(productInfoDo.getCommoditySku());
                productDo1.setCount(count);
                productDoList.add(productDo1);
            }
        }
        return productDoList;
    }

    @Override
    public Long getProductIdNoThrow(String sellerSKu, Long companyId) {
        final String sellerSku = sellerSKu.trim().replaceAll("\\n", "").replaceAll("　", "");
        LambdaQueryWrapper<ProductInfoDo> productWrapper = new LambdaQueryWrapper();
        productWrapper.eq(ProductInfoDo::getCompanyId, companyId);
        productWrapper.and(product -> {
            product.eq(ProductInfoDo::getCommoditySku, sellerSku).or().eq(ProductInfoDo::getStorageSku, sellerSku);
        });
        ProductInfoDo productInfoDo = dao.selectOne(productWrapper);
        if (productInfoDo == null) {
            QueryWrapper<ProductSkuMapDo> skuWrapper = new QueryWrapper<>();
            skuWrapper.eq("sub_sku", sellerSku);
            skuWrapper.eq("company_id", companyId);
            ProductSkuMapDo productSkuMapDo = productSkuMapDao.selectOne(skuWrapper);
            if (productSkuMapDo == null) {
                return 0L;
            }
            return productSkuMapDo.getProductInfoId();
        } else {
            return productInfoDo.getId();
        }
    }

    @Override
    public Map<Long, String> getProductListMap(Long companyId) {
        return dao.selectList(new LambdaQueryWrapper<ProductInfoDo>().eq(companyId != null, ProductInfoDo::getCompanyId, companyId))
                .stream().collect(Collectors.toMap(ProductInfoDo::getId, ProductInfoDo::getStorageSku));
    }

    @Override
    public ProductDetailRes detailAll(Long id) {
        ProductDetailRes detailRes = new ProductDetailRes();
        List<ProductSkuMapDetail> skuMapDetailList = new ArrayList<>();
        ProductInfoDo productInfoDo = dao.selectObject(id);
        BeanUtils.copyProperties(productInfoDo, detailRes);
        FileDo fileDo = fileDao.selectById(productInfoDo.getProductPictureFileId());
        if (fileDo != null) {
            detailRes.setFileName(fileDo.getFileName());
            detailRes.setProductPictureFileUrl(fileService.getFilePath(productInfoDo.getProductPictureFileId()));
        }
        DicBusinessItemDo dicBusinessItemDo = dicBusinessItemDao.selectById(productInfoDo.getProductType());
        if (dicBusinessItemDo != null) {
            detailRes.setProductTypeName(dicBusinessItemDo.getDicItemValue());
        }
        LambdaQueryWrapper<ProductSkuMapDo> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ProductSkuMapDo::getProductInfoId, productInfoDo.getId());
        List<ProductSkuMapDo> productSkuMapDos = productSkuMapDao.selectList(wrapper);
        if (!CollectionUtils.isEmpty(productSkuMapDos)) {
            for (ProductSkuMapDo skuMapDo : productSkuMapDos) {
                if (StringUtils.isEmpty(skuMapDo.getSubSku())) continue;
                ProductSkuMapDetail skuMapDetail = new ProductSkuMapDetail();
                skuMapDetail.setId(skuMapDo.getId());
                skuMapDetail.setSubSku(skuMapDo.getSubSku());
                skuMapDetailList.add(skuMapDetail);
            }
        }
        detailRes.setProductSkuMapDetailList(skuMapDetailList);
        if (!StaticDict.Product_Info_Type.Material.getValue().equals(productInfoDo.getTypeOfProduct())) {
            //组合产品
            detailRes.setChildProductList(this.getChildProductInfo(id, productInfoDo.getCompanyId()));
        }
        //耗材信息
        if (detailRes.getMaterialId() != null) {
            Map<String, String> map = new HashMap<>();
            map.put("id", detailRes.getMaterialId() + "");
            map.put("companyId", productInfoDo.getCompanyId() + "");

            List<MaterialDto> materialList = dao.getMaterialList(map);
            if (materialList.size() > 0) {
                detailRes.setMaterialRes(materialList.get(0));
            }
        }
        return detailRes;
    }

    //查询明细之后要执行的业务定制处理
    private Object handlerDetailAfter(Object res) {
        return res;
    }

    @Override
    public SingleResult pageInit() {
        return this.addInit();
    }

    @Override
    public PageResult getListPage(Map<String, String> map) {
        QueryWrapper<ProductInfoDo> wrapper = queryBuild(map);
        IPage<ProductInfoDo> page = pageInit(map);
        page = this.page(page, wrapper);
        List<ProductPageRes> resList = handlerListAfter(page.getRecords());
        PageResult result = new PageResult(resList, (int) page.getCurrent(), (int) page.getSize(), (int) page.getTotal(), (int) page.getPages());
        return result;
    }

    @Override
    public SingleResult importProductFile(MultipartFile file, Long userId, Long companyId) throws FileNotFoundException {
        if (StringUtils.isEmpty(file.getName())) {
            throw new BizExceptionI18(SysConstant.File_Name_Null);
        }
        String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".") + 1);
        if (!GlobalConstants.IMG_TYPE_XLS.equals(suffix.toUpperCase()) &&
                !GlobalConstants.IMG_TYPE_XLSX.equals(suffix.toUpperCase())) {
            throw new BizExceptionI18(SysConstant.File_Form_Incorrect);
        }
        if (companyId == null) {
            throw new BizExceptionI18(SysConstant.Login_Error_Company);
        }
        List<ProductInfoExcelImport> productInfoExcelImports = new ArrayList<>();
        try {
            productInfoExcelImports = ExcelUtils.importExcel(file, 1, 0, ProductInfoExcelImport.class);
        } catch (IOException e) {
            e.printStackTrace();
            throw new BizException(e.getMessage());
        }

        for (ProductInfoExcelImport excelData : productInfoExcelImports) {
            if (excelData.getTypeOfProduct() == null) {
                continue;
            }
            if (!StaticDict.Product_Info_Type.Common.getValue().equals(excelData.getTypeOfProduct()) && !StaticDict.Product_Info_Type.Combination.getValue().equals(excelData.getTypeOfProduct())) {
                throw new BizExceptionI18(SysConstant.Product_Import_Error);
            }
            if (excelData.getLength() == null) {
                throw new BizExceptionI18(SysConstant.Product_Length_Error);
            }
            if (excelData.getWidth() == null) {
                throw new BizExceptionI18(SysConstant.Product_Width_Error);
            }
            if (excelData.getHeight() == null) {
                throw new BizExceptionI18(SysConstant.Product_Height_Error);
            }
            if (excelData.getWeight() == null) {
                throw new BizExceptionI18(SysConstant.Product_Weight_Error);
            }
            if (excelData.getProductName() == null) {
                throw new BizExceptionI18(SysConstant.Product_Name_Error);
            }
            if (excelData.getCommodityName() == null) {
                throw new BizExceptionI18(SysConstant.Product_Name_JP_Error);
            }
            ProductAddReq addReq = new ProductAddReq();
            if (excelData == null || excelData.getProductName() == null || excelData.getCommoditySku() == null)
                continue;
            if (excelData.getReportPrice() == null)
                excelData.setReportPrice(0F);
            if (excelData.getSalePrice() == null)
                excelData.setSalePrice(0);
            BeanUtils.copyProperties(excelData, addReq);
            LambdaQueryWrapper<DicBusinessItemDo> wrapper = new LambdaQueryWrapper<DicBusinessItemDo>();
            wrapper.eq(DicBusinessItemDo::getDicItemValue, excelData.getProductType());
            DicBusinessItemDo itemDo = dicBusinessItemDao.selectOne(wrapper);
            if (itemDo != null)
                addReq.setProductType(itemDo.getId());
            List<ProductSkuMapAddReq> skuMapAddReqList = new ArrayList<>();
            if (StringUtils.isNotBlank(excelData.getSubSku())) {
                String[] strings = excelData.getSubSku().split(",");
                for (String s :
                        strings) {
                    ProductSkuMapAddReq subSku = new ProductSkuMapAddReq();
                    subSku.setSubSku(s);
                    skuMapAddReqList.add(subSku);
                }
            }
            addReq.setSkuMapAddReqList(skuMapAddReqList);
            if (excelData.getFileUrl() != null) {
                Long fileId = fileService.uploadExcelImage(excelData.getFileUrl(), userId);
                addReq.setProductPictureFileId(fileId);
            }
            //对于产品匹配耗材
            float productSize = excelData.getLength()
                    + excelData.getWidth()
                    + excelData.getHeight();
            LambdaQueryWrapper<DicBusinessItemDo> dicWrapper = new LambdaQueryWrapper();
            dicWrapper.eq(DicBusinessItemDo::getDicBusinessId, 32L);
            //找到所有的标签id
            List<Long> ids = dicBusinessItemDao.selectList(dicWrapper)
                    .stream().map(DicBusinessItemDo::getId).collect(Collectors.toList());
            LambdaQueryWrapper<StorageServiceProjectDo> sspWrapper = new LambdaQueryWrapper<>();
            sspWrapper.in(StorageServiceProjectDo::getType, ids);
            if ("是".equals(excelData.getNeedPackage()) || "要".equals(excelData.getNeedPackage()) ||
                    "需要".equals(excelData.getNeedPackage())) {
                List<StorageServiceProjectDo> storageServiceProjectDos = storageServiceProjectDao.selectList(sspWrapper);
                //选择第一个适用的耗材
                for (StorageServiceProjectDo storageServiceProjectDo : storageServiceProjectDos) {
                    if (storageServiceProjectDo.getCapacity() > productSize) {
                        addReq.setConsumables(storageServiceProjectDo.getId());
                        break;
                    }
                    //没有适合的包装耗材
                    if (storageServiceProjectDos.get(storageServiceProjectDos.size() - 1)
                            .getCapacity() < productSize) {
                        addReq.setConsumables(0L);
                    }
                }
            } else {
                addReq.setConsumables(1L);
            }
            //对装箱数设值
            if (StringUtils.isNotBlank(excelData.getPackageCount())) {
                addReq.setCasePack(Long.parseLong(excelData.getPackageCount()));
            } else {
                addReq.setCasePack(1L);
            }
            LambdaQueryWrapper<ProductInfoDo> productInfoWrapper = new LambdaQueryWrapper<>();
            productInfoWrapper.eq(ProductInfoDo::getCommoditySku, excelData.getCommoditySku().trim())
                    .eq(ProductInfoDo::getCompanyId, companyId);
            ProductInfoDo productInfoDo = baseMapper.selectOne(productInfoWrapper);
            if (productInfoDo == null) {
                add(addReq, userId, companyId);
            } else {
                ProductUpdateReq updateReq = new ProductUpdateReq();
                BeanUtils.copyProperties(excelData, updateReq);
                updateReq.setId(productInfoDo.getId());
                this.update(updateReq, userId, companyId);
            }
        }

        return null;
    }

    //查询分页列表之后对列表数据的处理
    private List<ProductPageRes> handlerListAfter(List<ProductInfoDo> list) {
        List<ProductPageRes> result = new ArrayList<>();
        if (!CollectionUtils.isEmpty(list)) {
            for (ProductInfoDo infoDo : list) {
                ProductPageRes res = new ProductPageRes();
                BeanUtils.copyProperties(infoDo, res);
                res.setProductId(infoDo.getId());
                DicBusinessItemDo businessItemDo = dicBusinessItemDao.selectById(infoDo.getProductType());
                if (businessItemDo != null) {
                    res.setProductType(businessItemDo.getDicItemValue());
                }
                if (infoDo.getProductPictureFileId() != null) {
                    res.setProductPictureFileUrl(fileService.getFilePath(infoDo.getProductPictureFileId()));
                }
                result.add(res);
            }
        }
        return result;
    }

    private IPage<ProductInfoDo> pageInit(Map<String, String> map) {
        IPage<ProductInfoDo> page = new Page();
        page.setSize(StringUtils.isNotBlank(map.get("pageSize")) ? Long.parseLong(map.get("pageSize")) : 10);
        page.setCurrent(StringUtils.isNotBlank(map.get("current")) ? Long.parseLong(map.get("current")) : 1);
        return page;
    }

    private QueryWrapper<ProductInfoDo> queryBuild(Map<String, String> map) {
        QueryWrapper<ProductInfoDo> wrapper = new QueryWrapper<>();
        if (StringUtils.isNotBlank(map.get("keyword"))) {
            wrapper.and(i -> i.like("commodity_sku", map.get("keyword"))
                    .or().like("storage_sku", map.get("keyword"))
                    .or().like("commodity_name", map.get("keyword"))
                    .or().like("product_name", map.get("keyword")));
        }
        if (StringUtils.isNotBlank(map.get("productType"))) {
            wrapper.eq("product_type", map.get("productType"));
        }
        if (StringUtils.isNotBlank(map.get("cwSkuCodeList"))) {
            wrapper.in("commodity_sku", Arrays.asList(map.get("cwSkuCodeList").split(",")));
        }
        wrapper.eq("type", 1);
        wrapper.eq("company_id", map.get("companyId")).orderByDesc("id");
        return wrapper;
    }

    @Override
    public String exportProductCodePdf(Long id, int count, HttpServletResponse response) {
        ProductInfoDo productInfoDo = dao.selectObject(id);
        if (productInfoDo == null) throw new BizExceptionI18(SysConstant.Product_NotExist);
        if (count > 999) throw new BizExceptionI18(SysConstant.Product_CodeExport_Error);
        String name = productInfoDo.getCommoditySku() + "x" + count + "_" + TimeUtils.getCurrentDateFormat("HHmmss");
        PdfUtils pdfUtils = new PdfUtils(name, response);
        pdfUtils.printProductCodePdf(productInfoDo.getStorageSku(), productInfoDo.getCommodityName(), productInfoDo.getCommoditySku(), count);
        return name;
    }


    /**
     * 新版打印条形码 一页一个
     *
     * @param map
     * @param id
     * @param length
     * @param width
     * @param count
     * @param response
     */
    @Override
    public void printBarCodePdf(Map<String, String> map, Long id, int length, int width, int count, HttpServletResponse response) {
        ProductInfoDo productInfoDo = dao.selectById(id);
        if (productInfoDo == null) {
            throw new BizExceptionI18(SysConstant.Product_NotExist);
        }
        if (count > 999) {
            throw new BizExceptionI18(SysConstant.Product_CodeExport_Error);
        }
        Map<String, String> attributeMap = new TreeMap<>();
        if (StringUtils.isNotBlank(map.get("commoditySku"))) {
            attributeMap.put("1commoditySku", productInfoDo.getCommoditySku());
        }
        if (StringUtils.isNotBlank(map.get("storageSku"))) {
            attributeMap.put("2storageSku", productInfoDo.getStorageSku());
        }
        if (StringUtils.isNotBlank(map.get("productName"))) {
            attributeMap.put("3productName", StringUtils.isBlank(productInfoDo.getCommodityName()) ? productInfoDo.getProductName() : productInfoDo.getCommodityName());
        }
        if (StringUtils.isNotBlank(map.get("fnSku")) && StringUtils.isNotBlank(productInfoDo.getFnSku())) {
            attributeMap.put("4fnSku", productInfoDo.getFnSku());
        }

        if (StringUtils.isNotBlank(map.get("madeInChina"))) {
            attributeMap.put("5madeInChina", "Made In China");
        }
        if (StringUtils.isNotBlank(map.get("printDate"))) {
            attributeMap.put("7printDate", DateUtils.dateFormatToString(new Date(), "yyyy-MM-dd"));
        }
        if (StringUtils.isNotBlank(map.get("productSpec"))) {
            attributeMap.put("6productSpec", productInfoDo.getLength() + "cm x" + productInfoDo.getWidth() + "cm x" + productInfoDo.getHeight() + "cm");
        }

//        attributeMap.put("productName", productInfoDo.getProductName());
//        attributeMap.put("sku", productInfoDo.getCommoditySku());
//        attributeMap.put("madeInChina", "made IN China");
        String name = productInfoDo.getCommoditySku() + "x" + count + "_" + TimeUtils.getCurrentDateFormat("HHmmss");
        if (length == 210 && width == 297) {
            //a4打印 一行三个
            BarCodePdfUtils.printPdfA4(attributeMap, count, productInfoDo.getStorageSku(), name, response);
        } else {
            //其他纸张类型 一张一个
            BarCodePdfUtils.printBarCodePdf(attributeMap, length, width, count, productInfoDo.getStorageSku(), name, response);
        }
    }


    @Override
    public PageResult getListPageAll(Map<String, String> map) {
        IPage<ProductInfoDo> page = pageInit(map);
        List<ProductInfoDo> productInfoDos = dao.selectAll(page, map, null);
        List<ProductPageRes> resList = handlerListAfter(productInfoDos);
        PageResult result = new PageResult(resList, (int) page.getCurrent(), (int) page.getSize(), (int) page.getTotal(), (int) page.getPages());
        return result;
    }


    @Override
    public void exportProduct(Map<String, String> map, HttpServletResponse response) throws IOException {
        List<ProductInfoDo> productInfoDos = dao.selectAll(map, null);

        List<ProductInfoExportVo> exportVoList = new ArrayList<>();
        for (ProductInfoDo productInfoDo : productInfoDos) {
            ProductInfoExportVo exportVo = new ProductInfoExportVo();
            BeanUtils.copyProperties(productInfoDo, exportVo);
            exportVoList.add(exportVo);
        }

        ExcelUtils.exportExcel(exportVoList, ProductInfoExportVo.class, "SKU信息", new ExportParams(),  response);

    }

    /**
     * 获取组合产品 的子产品信息
     *
     * @return
     */
    public List<ProductPageRes> getChildProductInfo(Long id, Long companyId) {
        List<ProductInfoDo> list = new ArrayList<>();

        List<ProductCombinationDo> combinationDoList = combinationDao.selectList(new LambdaQueryWrapper<ProductCombinationDo>().eq(ProductCombinationDo::getParentId, id));
        Map<Long, List<ProductCombinationDo>> mapList = combinationDoList.stream().collect(Collectors.groupingBy(ProductCombinationDo::getChildId));
        List<Long> ids = combinationDoList.stream().map(ProductCombinationDo::getChildId).collect(Collectors.toList());
        if (ids.size() > 0) {
            Map<String, String> map = new HashMap<>();
            map.put("companyId", companyId + "");
            list = dao.selectAll(map, ids);
        }
        List<ProductPageRes> resList = handlerListAfter(list);
        for (ProductPageRes productPageRes : resList) {
            if (mapList.get(productPageRes.getId()) != null) {
                productPageRes.setCount(mapList.get(productPageRes.getId()).get(0).getCount());
                productPageRes.setEffective(mapList.get(productPageRes.getId()).get(0).getEffective());
                productPageRes.setEffectBeginTime(mapList.get(productPageRes.getId()).get(0).getEffectBeginTime());
                productPageRes.setEffectEndTime(mapList.get(productPageRes.getId()).get(0).getEffectEndTime());

            }
        }
        return resList;
    }
}
